/*
 *--------------------------------------------------------------------------
 *   Battlefield - A Realtime Network Multiplayer Game
 *   =======================================================
 *   Developed by Group D02 - 2009/2010 Semester 4 - CS2103
 *     Harry Nguyen Duy Hoang <nnduyhoang@yahoo.co.uk>
 *     Kent Chng Siang Rong <fivefootway@gmail.com>
 *     Lim Yong Peng <limpeng1986@gmail.com>
 *     Loh Xiankun <u0807185@nus.edu.sg>
 *   Instructed by
 *     Dr. Damith C.Rajapakse <damith@gmail.com>
 *   =======================================================
 *   $Id: UnitModelManager.java 588 2010-07-26 13:52:44Z YongPeng $
 *   $LastChangedDate: 2010-07-26 13:52:44 +0000 (Mon, 26 Jul 2010) $
 *   $LastChangedBy: YongPeng $
 *--------------------------------------------------------------------------
 */
package battlefield.manager;

import battlefield.BattlefieldException;
import battlefield.entity.UnitModel;
import battlefield.util.DataUtils;
import battlefield.util.IDGenerator;
import battlefield.util.SerializationUtils;
import java.util.ArrayList;
import java.util.HashMap;

/**
 *
 * @author Harry Nguyen
 */
public class UnitModelManager extends HashMap<Integer, UnitModel> {

    private IDGenerator idGenerator;

    /**
     * Constructs a UnitModelManager that will manage the different models of
     * unit used in this game
     */
    public UnitModelManager() {
        idGenerator = new IDGenerator();
        String[] files = DataUtils.readLines(this.getClass().getResourceAsStream("/battlefield/unitmodels.txt"));
        for (String file : files) {
            load(file);
        }
    }

    /**
     * Returns the model of unit 
     * @param unitModelId
     * @return
     * @throws BattlefieldException
     */
    public UnitModel get(int unitModelId) throws BattlefieldException {
        if (super.get(unitModelId) == null) {
            throw new BattlefieldException("Unit Model not found.");
        }

        return super.get(unitModelId);
    }

    /**
     * Returns a list of all UnitModels used in this game
     * @return ArrayList
     */
    public ArrayList<UnitModel> getUnitModels() {
        return new ArrayList<UnitModel>(this.values());
    }

    private void load(String fileName) {
        Object object = SerializationUtils.load(this.getClass().getResourceAsStream(fileName));
        if (object != null && object instanceof UnitModel) {
            UnitModel model = (UnitModel) object;
            model.setId(idGenerator.next());
            put(model.getId(), model);
        }
    }
}
